<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Log;
use Route;
use App\Traits\AuthTrait;

class AuthController extends ApiController
{
    use AuthTrait;

    /**
     * 调用认证接口获取授权码   
     *  
     * @param  Request  $request
     * @param string $client_name 客户端名称
     * @return Response
     */     
    protected function oauthToken(Request $request, $client_name)
    {
        $this->validate($request, [
            'username' => 'required',
            'password' => 'required',
        ]);

        // 请求密码授权令牌
        $res = $this->oauthPassport($request->username, $request->password, $client_name);

        if ($res) {
            $request->request->add($res);
            $proxy = Request::create(
                'oauth/token',
                'POST'
            );
            return Route::dispatch($proxy);
        }

        return $this->failed('登录失败', 401);
    }

    /**
     * 普通用户登录
     *
     * @param  Request  $request
     * @return Response
     */    
    public function users(Request $request)
    {
        return $this->oauthToken($request, '用户');
    }
    
    /**
     * 管理员登录
     *
     * @param  Request  $request
     * @return Response
     */      
    public function admin(Request $request)
    {
        config(['auth.guards.api.provider' => 'admin']);
                
        return $this->oauthToken($request, '管理员');        
    }

}
